package com.xzit.rcpyxt.config;

import com.xzit.rcpyxt.constant.MessageCode;
import com.xzit.rcpyxt.exceptions.CustomeException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyControllerAdvice {

    private final static Logger logger = LogManager.getLogger(MyControllerAdvice.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> errorHandler(Exception exception) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", MessageCode.SYSTEM_ERROR.getCode());
        map.put("message", MessageCode.SYSTEM_ERROR.getMessage());
        logger.error("系统异常====》", exception);
        return map;
    }

    /**
     * 拦截捕捉自定义异常 CustomeException.class
     */
    @ResponseBody
    @ExceptionHandler(value = CustomeException.class)
    public Map<String, Object> myErrorHandler(CustomeException customeException) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", customeException.getCode());
        map.put("message", customeException.getMessage());
        map.put("data", customeException.getData());
        logger.error("自定义异常====》", customeException);
        return map;
    }

}